package com.xzy.mybatis.service;

import com.xzy.mybatis.entity.TestA;
import com.xzy.mybatis.entity.TestB;
import com.xzy.mybatis.entity.TestC;
import com.xzy.mybatis.event.CustomerEvent;
import com.xzy.mybatis.mapper.TestAMapper;
import com.xzy.mybatis.mapper.TestBMapper;
import com.xzy.mybatis.mapper.TestCMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author xzy.xiao
 * @date 2023/10/11  9:42
 */
@Service
public class TestAServiceImpl implements TestAService {

    private final TestAMapper testAMapper;
    private final TestBMapper testBMapper;
    private final TestCMapper testCMapper;
    private final ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    public TestAServiceImpl(TestAMapper testAMapper, TestBMapper testBMapper, TestCMapper testCMapper, ApplicationEventPublisher applicationEventPublisher) {
        this.testAMapper = testAMapper;
        this.testBMapper = testBMapper;
        this.testCMapper = testCMapper;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void transactionTest1(boolean isTestASuccess, boolean isTestBSuccess, boolean isTestCSuccess) {
        String batchNo = LocalDateTime.now().toString();

        applicationEventPublisher.publishEvent(new CustomerEvent(this, batchNo));

        createA(isTestASuccess, batchNo);
        createB(isTestBSuccess, batchNo);
        createC(isTestCSuccess, batchNo);
    }

    private void createA(boolean isSuccess, String remark) {
        testAMapper.insert(new TestA(remark));

        if (!isSuccess) {
            throw new IllegalArgumentException();
        }
    }

    private void createB(boolean isSuccess, String remark) {
        testBMapper.insert(new TestB(remark));

        if (!isSuccess) {
            throw new IllegalArgumentException();
        }
    }

    private void createC(boolean isSuccess, String remark) {
        testCMapper.insert(new TestC(remark));

        if (!isSuccess) {
            throw new IllegalArgumentException();
        }
    }
}
